import axios, {InternalAxiosRequestConfig, AxiosResponse} from 'axios'
import {isNull} from '@/utils'
import {message} from '@/components/popup'

export const request = axios.create({
    baseURL: '/api',
    timeout: 5000,
})

// 请求拦截器
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
        const token = localStorage.getItem('token')
        if (!isNull(token)) {
            config.headers.Authorization = token
        }
        return config
    },
    (error) => {
        return Promise.resolve(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.data?.code > 200) {
            message.error(response.data?.msg)
        }
        return response.data
    },
    (error) => {
        if (error.response) {
            return Promise.reject(error.response)
        }

        if (error.response?.status > 200) {
            return Promise.reject(error)
        }

        return Promise.reject(error)
    }
)
